from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from .models import OauthQQuser
from rest_framework_jwt.views import api_settings

from .utils import generate_save_user_token
from .oauthSerislizer import QQAuthUserSerializer
from carts.utils import merge_cart_cookie_to_redis


class QQAuthURLView(APIView):
    """返回qq登陆页面"""

    def get(self, request):
        # next 是从那个页面进入到qq中心，如果登陆成功将返回这个页面（也可以固定一个页面，这个看前段传来的）
        next = request.query_params.get("next")

        print(request.GET)
        # 如果next是空的值返回首页
        if next is None:
            next = "/"

        # 获取qq登陆页面
        # 导入qqlogintool SDK工具包
        # 导入qq配置文件
        # 使用sdk里面提供的方法拼接url地址返回

        oauth = OAuthQQ(settings.QQ_CLIENT_ID, settings.QQ_CLIENT_SECRET, settings.QQ_REDIRECT_URI, state=next)

        login_url = oauth.get_qq_url()

        return Response({"login_url": login_url})


# class QQAuthUserView(GenericAPIView):
class QQAuthUserView(CreateAPIView):
    """用户登陆扫码回调处理"""

    # 指定序列化器
    # 重写post方法
    serializer_class = QQAuthUserSerializer

    def get(self, request):
        # 获取前端url。code值
        code = request.query_params.get("code")

        # 判断code茶树是否为空
        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取跳转页面url(用于保存登录成功后的跳转页面路径,stats)
        next = request.query_params.get("state")

        # 创建工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        try:
            # 使用code访问qq服务器获取access_token
            access_token = oauth.get_access_token(code)
            print(access_token)
            # 使用access_token获取openid
            openid = oauth.get_open_id(access_token)
            print(openid)
        except Exception as e:
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 根据openid查询数据库是否存在该用户
        try:
            oauth_suer = OauthQQuser.objects.get(openid=openid)
            # 使用get查询不到,会报错

        except OauthQQuser.DoesNotExist:
            # 用户是第一次使用QQ登录时返回，其中包含openid，
            # 用于绑定身份使用，注意这个是我们自己生成的
            # Itsdangrous生成的临时票据，里面隐藏了openid
            access_token_openid = generate_save_user_token(openid)
            return Response({
                "access_token": access_token_openid
            })


        else:
            # 如果以查询到用户绑定 直接返回用户以jwt方式返回
            # token，username，user_id
            # 如果openid已绑定美多商城用户，直接生成JWT token，并返回
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # 获取oauth_user关联user
            user = oauth_suer.user
            print(oauth_suer)
            print(user)
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            # 合並購物方法
            response = merge_cart_cookie_to_redis(request, user, response)

            return response

    # def post(self, request):
    #     """用户openid帮顶"""
    #     # 获取序列器对象
    #     serializers = self.get_serializer(data=request.data)
    #     # 校验数据
    #     serializers.is_valid(raise_exception=True)
    #     # 保存数据
    #     user = serializers.save()
    #
    #     # 5、发送数据 jwt
    #
    #     # 创建jwt
    #     jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    #     jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
    #
    #     # 放入载荷
    #     payload = jwt_payload_handler(user)
    #     # 生成token
    #     token = jwt_encode_handler(payload)
    #
    #     return Response({
    #         "token": token,
    #         "id": user.id,
    #         "username": user.username
    #     })

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)

        # 合并购物车
        response = merge_cart_cookie_to_redis(request, self.user, response)
        return response
